import { useMemo } from 'react';
import { DescriptionsTypeAPI } from '../src/type';
import { Form } from 'antd';

/**
 * @useDescriptionsType 表格表单hooks
 * @param options 配置项
 * @returns
 */
export function useDescriptionsType(options: DescriptionsTypeAPI.IDescriptionsType) {
  // 表单实例
  const [form] = Form.useForm();

  const { basicForm = form, schemas, labelWidth = 180, headerSchema = {}, disabled = false, name = 'description-form', isShowNumTitle = true } = options;

  /** 处理合并 colSpan */
  const fieldItemHandle = (fieldList: Record<string, any>[]) => {
    const tempData: any = [];
    let num = 0;
    fieldList?.map((item: any) => {
      if (item?.ishidden) return;
      if (!tempData[num]) tempData[num] = [];
      if (!item.colSpan || item.colSpan == 1) {
        tempData[num].push(item);
        if (tempData[num].length == 2) num++;
      } else {
        tempData[num].push(item);
        num++;
      }
    });
    return tempData;
  };

  // 遍历出符合规范的数据
  const dataSource = useMemo(() => {
    const newSchemas: any = schemas?.filter((itemAll: any) => !itemAll?.ishidden);
    const schemasList = newSchemas.map((item: any, index: number) => {
      return {
        ...item,
        title: item?.title,
        titleText: item?.title,
        fieldChildren: item?.fieldChildren ? fieldItemHandle(item?.fieldChildren) : [],
      };
    });
    return schemasList;
  }, [schemas]);

  return [
    {
      form: basicForm,
      name,
      dataSource,
      headerSchema,
      labelWidth,
      disabled,
      isShowNumTitle,
    } as any,
    basicForm,
  ];
}
